package chexuan.game.service.io.connection;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

import chexuan.game.bean.packet.common.Packet;
import chexuan.game.exception.NotRegisteredServiceException;
import chexuan.game.interfaces.service.InterfaceTask;
import chexuan.game.util.SystemUtil;

public class PacketReaderTask implements InterfaceTask {

	private static final String TASK_NAME = "TASK - PacketReader";

	private SelectionKey readableKey = null;

	public static PacketReaderTask createTask(SelectionKey readableKey) {
		return new PacketReaderTask(readableKey);
	}

	private PacketReaderTask(SelectionKey readableKey) {
		this.readableKey = readableKey;
	}

	@Override
	public void run() {
		try {
			Packet packet = readPacket();

			int connectionId = SystemUtil.getIoService().getConnectionId(
					(SocketChannel) this.readableKey.channel());
			submitPacketHanderTask(connectionId, packet);
		} catch (NotRegisteredServiceException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getTaskName() {
		return TASK_NAME;
	}

	private Packet readPacket() throws IOException {
		SocketChannel channel = (SocketChannel) readableKey.channel();
		Packet packet = Packet.createPacket();
		ByteBuffer headerBuffer = packet.allocatePacketHeaderBuffer();
		channel.read(headerBuffer);
		packet.readHeader(headerBuffer);
		ByteBuffer bodyBuffer = packet.allocatePacketBodyBuffer();
		packet.readBody(bodyBuffer);
		return packet;
	}

	private void submitPacketHanderTask(int connectionId, Packet packet)
			throws NotRegisteredServiceException {
		SystemUtil.getTaskService().submit(
				PacketHandlerTask.createTask(connectionId, packet));
	}
}
